//
//  CacheManager.swift
//  PMS
//
//  Created by 何海涛 on 15/10/15.
//  Copyright © 2015年 途家. All rights reserved.
//

import Foundation

public protocol ICacheable {
    func add<T>(_ key : String, value : T, offsetMinutes offset : TimeInterval)
    func get<T>(_ key : String) -> T?
    func get<T>(_ key : String, valueProvider : () -> T, offsetMinutes offset : (_ result : T) -> TimeInterval) -> T? // offset : minutes
    func remove(_ key : String)
    func clear()
}

public class LocalCache : ICacheable {
    
    init() {
        dataContainer = Dictionary<String,(Date,Any)>()
    }
    
    public var dataContainer : Dictionary<String,(Date,Any)>
    
    public func get<T>(_ key: String, valueProvider: () -> T, offsetMinutes offset: (_ result : T)-> TimeInterval) -> T? {
        let cache = dataContainer[key]
        if cache == nil || cache!.0 < Date() { //没有或者已过期
            let result = valueProvider()
            let expire = Date(timeIntervalSinceNow: offset(result) * 60)
            addCache(key, value: result, expire: expire)
            return result
        }
        return cache!.1 as? T
    }
    
    public func get<T>(_ key: String) -> T? {
        let cache = dataContainer[key]
        if cache == nil || cache!.0 < Date() { //没有或者已过期
            return nil
        }
        return cache!.1 as? T
    }
    
    public func add<T>(_ key: String, value: T, offsetMinutes offset: TimeInterval) {
        addCache(key, value: value, expire: Date(timeIntervalSinceNow: offset * 60))
    }
    
    fileprivate func addCache(_ key : String, value : Any, expire : Date) {
        dataContainer[key] = (expire, value)
    }
    
    public func remove(_ key: String) {
        dataContainer.removeValue(forKey: key)
    }
    
    public func clear() {
        dataContainer.removeAll()
    }
}

public class CacheManager {
    public static let localCache : ICacheable = LocalCache()
}

